const Router = require('koa-router');
const tool = require("../../tools/tool");
const router = new Router();
const {db, Op, QueryTypes} = require("../../models/db");
const tools = require("../../tools/tool");
// 领单收款，扫描销售票据
router.post('/ldsk/findSaleBill', async ctx => {
    let tenantId = ctx.user.tenantId;
    let scanInfo = ctx.request.body.scanInfo;
    if (!scanInfo) {
        return ctx.err('未找到数据');
    }
    let ret = scanInfo.split('-');
    let transType = tool.xe.toNumber(ret[0])
    let billId = tool.xe.toNumber(ret[1])
    // 销售票据
    if (transType === 150601 || transType === 150602 || transType === 150603) {
        let sqlInvoice = `
            select a.id,a.id billId,a.totalAmount,a.arrears,a.billNo srcBillNo,a.transTypeName srcTransTypeName,
                   a.billDate srcBillDate,a.salesId,a.buId,a.transType srcTransType,a.billState srcBillState,
            b.name buName,c.name salesName,isnull(a.hxAmount,0) as hxAmount from 
           (
              select * from invoice where tenantId=${tenantId} and id=${billId}
            ) a left join contact b on a.buId=b.id left join admin c on a.salesId=c.id 
        `
        let bill = await db.query(sqlInvoice, {type: QueryTypes.SELECT, plain: true})
        if(!bill) return ctx.err('未找到该票据')
        if(bill.srcBillState === 'draft') return ctx.err('请先审核票据')
        if(bill.srcBillState === 'del') return ctx.err('票据已被删除')
        if(bill.srcTransType === 150602) {
            bill.arrears = tool.xe.toFixed(-bill.arrears,2)
        } else {
            bill.arrears = tool.xe.toFixed(bill.arrears, 2)
        }
        let left = tool.xe.subtract(bill.arrears, bill.hxAmount)
        if(left === 0) {
            return ctx.err('当前没有欠款')
        }
        bill.leftAmount = left
        bill.nowCheck = bill.leftAmount
        bill.yhAmount = 0
        return ctx.suc('', bill);
    }
    return ctx.err('还未更新此类票据信息')
})





module.exports = router;